package com.kinghunt.misp.common.utils.easyExcel;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.kinghunt.misp.common.enums.userx.RoleEnum;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * EasyExcel 角色转换器
 * 1- 万博超级管理员
 * 2- 万博系统管理员
 * 3- 机构管理员
 * 4- 读者-老师
 * 5- 读者-学生
 * 6- 读者-IP免登录
 */
public class RoleConverter implements Converter<Long> {
    @Override
    public Class<?> supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    /**
     * for read
     *
     * @param context
     * @return
     */
    @Override
    public Long convertToJavaData(ReadConverterContext<?> context) {
        String value = context.getReadCellData().getStringValue();
        if (StringUtils.isBlank(value)) {
            return RoleEnum.ORG_STU.getId();
        }
        for (RoleEnum role : RoleEnum.values()) {
            if (role.getName().equals(value)) {
                return role.getId();
            }
        }
        return RoleEnum.ORG_STU.getId();
    }

    /**
     * for write
     *
     * @return
     */
    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<Long> context) {
        Long value = context.getValue();

        if (Objects.isNull(value)) {
            return new WriteCellData<>(RoleEnum.ORG_STU.getName());
        }
        for (RoleEnum role : RoleEnum.values()) {
            if (role.getId().equals(value)) {
                return new WriteCellData<>(role.getName());
            }
        }
        return new WriteCellData<>(RoleEnum.ORG_STU.getName());
    }
}
